const Koa = require("koa");
const app = new Koa();
const config = require("./config/index");
const process = require("process");
const logger = require("./utils/logger.js");
// console 封装
const chalk = require("./utils/chalk");
// 获取ip
const { getIPv4 } = require("./utils/utils");

const middleware = require("./middleware/index");
middleware(app);

process.on("uncaughtException", function (err) {
  //打印出错误
  console.log(err);
  //打印出错误的调用栈方便调试
  console.log(err.stack);
  logger.logError("uncaughtException", err);
});


app.use(async (ctx, next) => {
  const start = new Date(); // 响应开始时间
  let intervals; // 响应间隔时间
  try {
    await next();
    intervals = new Date() - start;
    console.log("intervals",intervals);
    const { user = {} } = ctx.state;
    logger.logResponse(ctx, intervals); //记录响应日志
  } catch (error) {
    intervals = new Date() - start;
    console.log("intervals",intervals);
    const { user = {} } = ctx.state;
    logger.logError(ctx, error, intervals); //记录异常日志
  }
});

const routers = require("./routes/index");
routers(app);

app.listen(config.port, (err) => {
  if (!err) {
    console.log(
      "Listening at " +
        chalk.green(`http://localhost:${config.port}\n`) +
        "or at " +
        chalk.green(`http://${getIPv4()}:${config.port}`)
    );
  } else {
    console.log(chalk.red(err));
  }
});
